import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_demo/entities/article_detail.dart';
import 'package:flutter_demo/entities/article_item.dart';
import 'package:flutter_demo/utils/dom_parser.dart';
import 'package:flutter_demo/views/loading_container.dart';
import 'package:get/get.dart';
import 'package:html/parser.dart' as htmlparser;
import 'package:html/dom.dart' as dom;
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

class ArticleDetailController extends GetxController {
  var detail = ArticleDetail().obs;
  var detailLoadingStatus = LoadStatus.loading.obs;

  // 下载链接
  var links = List<Link>.empty(growable: true).obs;
  var linkLoadingStatus = LoadStatus.loading.obs;
  var linkHtml = "".obs;

  var scrollController = ItemScrollController();

  @override
  onReady() {
    super.onReady();
    getDetail(Get.arguments);
  }

  getDetail(ArticleItem item) async {
    detailLoadingStatus.value = LoadStatus.loading;
    final response = await Dio().get<String>(item.link);
    dom.Document document = htmlparser.parse(response.data);
    final content = document.getElementsByClassName("entry-content")[0];
    // 图文内容
    final items = content.children;
    final articleDetail = ArticleDetail();
    articleDetail.title = item.title;
    articleDetail.tags = item.tags;
    articleDetail.link = item.link;
    for (final p in items) {
      // 视频
      if (p.className == "wideo") {
        final videoScript = document.getElementsByTagName("script").firstWhereOrNull((element) => element.text.contains("DPlayer"));
        if (videoScript != null) {
          final url = DomParser.parseVideo(videoScript);
          Get.log("aaac, $url");
          if (url != null) {
            final item = Item();
            item.type = "video";
            item.content = url;
            articleDetail.items.add(item);
            final link = Link();
            link.title = "视频下载";
            link.href = item.content.toString();
            links.add(link);
          }
        }
      } else {
        var imgs = p.getElementsByTagName("img");
        if (imgs.isNotEmpty) {
          for (final img in imgs) {
            var item = Item();
            item.type = "img";
            item.content = img.attributes["src"];
            articleDetail.items.add(item);
          }
        } else if (p.text.isNotEmpty && !p.text.contains("DPlayer")) {
          var item = Item();
          item.type = "text";
          item.content = p.innerHtml;
          articleDetail.items.add(item);
        }
      }
    }

    // final scripts = document.getElementsByTagName("script");
    // final videoScript = scripts.firstWhereOrNull((element) => element.text.contains("DPlayer"));
    // if (videoScript != null) {
    //   final url = DomParser.parseVideo(videoScript);
    //   if (url != null) {
    //     final item = Item();
    //     item.type = "video";
    //     item.content = url;
    //     articleDetail.items.add(item);
    //     final link = Link();
    //     link.title = "视频下载";
    //     link.href = item.content.toString();
    //     links.add(link);
    //   }
    // }

    // comments
    var commentDocs = document.getElementsByClassName("comment-list");
    if (commentDocs.isNotEmpty) {
      var commentDoc = commentDocs[0];
      for (var li in commentDoc.children) {
        final comment = Comment();
        comment.avatar = li.getElementsByClassName("avatar")[0].attributes["data-src"].toString();

        var cite = li.getElementsByTagName("cite")[0];
        if (cite.className.contains("vip")) {
          comment.isVip = true;
        }
        comment.nickname = cite.text.toString().trim();
        comment.createTime = li.getElementsByTagName("time")[0].text.toString().trim();
        comment.content = li.getElementsByClassName("comment-body")[0].text.toString().trim();
        articleDetail.comments.add(comment);
      }
    }

    // hots
    var hots = document.getElementsByClassName("posts")[0];
    for (var hot in hots.children) {
      var a = hot.getElementsByTagName("a")[0];
      var img = a.getElementsByTagName("img")[0];
      var item = ArticleItem();
      item.title = hot.text.trim();
      item.cover = img.attributes["data-src"];
      item.link = a.attributes["href"].toString();
      articleDetail.hots.add(item);
    }
    detail(articleDetail);
    detailLoadingStatus.value = LoadStatus.success;

    getDownloadLinks();
  }

  getDownloadLinks() async {
    //https://fourpetal.com/go/?post_id=30016
    final dio = Dio()..options = BaseOptions(followRedirects: true);
    try {
      var response = await dio.get<String>("https://fourpetal.com/go?post_id=${detail.value.id}");
      final reg = RegExp(r"(https?)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
      final match = reg.firstMatch(response.data!);
      if (match != null) {
        final url = response.data!.substring(match.start, match.end);
        response = await dio.get<String>(url);
        dom.Document document = htmlparser.parse(response.data);
        final content = document.getElementsByClassName("entry-content")[0];
        linkHtml.value = content.innerHtml;
        var index = 0;
        for (var p in content.children) {
          final aList = p.getElementsByTagName("a");
          if (aList.isEmpty) {
            final link = Link();
            if (p.text.contains("baidu")) {
              link.title = "百度网盘";
              link.href = p.text.trim().substring(4);
              if (!link.href.contains("pwd")) {
                final pwd = _getBaiduPwd(content.children[index + 1]);
                link.href += "?pwd=$pwd";
              }
              links.add(link);
            }
          } else {
            for (var element in aList) {
              final link = Link();
              final href = element.attributes["href"];
              link.href = href.toString();
              if (href?.contains("baidu") == true) {
                link.title = "百度网盘";
                if (!link.href.contains("pwd")) {
                  final pwd = _getBaiduPwd(content.children[index + 1]);
                  link.href += "?pwd=$pwd";
                }
                if (index != 0) {
                  final pre = content.children[index - 1].text.trim();
                  if (pre.isNotEmpty && !pre.startsWith("提取码")) {
                    link.desc = pre;
                  }
                }
                links.add(link);
              } else if (href?.contains("quark") == true) {
                link.title = "夸克网盘";
                link.desc = p.text.substring(0, p.text.indexOf("\n"));
                links.add(link);
              } else if (href?.contains("aliyun") == true) {
                link.title = "阿里云";
                links.add(link);
              } else if (href?.contains("sharepoint") == true) {
                link.title = "OneDrive";
                links.add(link);
              } else if (href?.contains("switch520") == false) {
                link.title = p.text.toString();
                links.add(link);
              }
            }
          }
          index++;
        }
      }
    } catch (e) {
      Get.log("get download link err: $e");
    }

    if (links.isEmpty) {
      linkLoadingStatus.value = LoadStatus.empty;
    } else {
      linkLoadingStatus.value = LoadStatus.success;
    }
  }

  scrollToComment() {
    scrollController.scrollTo(index: 1, duration: const Duration(milliseconds: 300), curve: Curves.easeInOutCubic);
  }

  String _getBaiduPwd(dom.Element element) {
    final text = element.text.trim();
    return text.substring(text.length - 4, text.length);
  }
}
